<!-- 后端数据不明，等待测试，这里面接口没改，用的是通用接口，应该用/teacher/course/page，查询接口也要改成通用接口-->
<template>
  <div>
    <el-container>
      <el-main>
        <h1>当前学期我开设的课程</h1>
        <el-card>
          <!-- 查询列表，后面要加方法返回getCourselist -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入要查询的开设课程名称"  v-model="courseName">
            <el-button slot="append" icon="el-icon-search" @click="searchCourse()">
            <!-- 获取用户列表   -->
            </el-button>
          </el-input>
        </el-col>
      </el-row>
      <!-- 课程表格 -->
      <el-table
          :data="tableData"
          border
          style="width: 100%">
        <el-table-column
            fixed
            prop="name"
            label="课程名称"
            width="200">
        </el-table-column>
        <el-table-column
            prop="courseId"
            label="课程号"
            width="150">
        </el-table-column>
        <el-table-column
            prop="credit"
            label="学分"
            width="150">
        </el-table-column>
        <el-table-column
            prop="period"
            label="时间"
            width="150">
        </el-table-column>
        <el-table-column
            prop="collegeId"
            label="课程ID"
            width="150">
        </el-table-column>
        <el-table-column
            label="操作"
            width="100">
          <template slot-scope="scope">
            <el-popconfirm
                confirm-button-text='取消开设'
                cancel-button-text='取消'
                icon="el-icon-info"
                title="确定取消开设？"
                @confirm="handleDelete(scope.row)"
            >
              <el-button slot="reference" type="danger" size="small">取消开设</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
          <el-pagination
        :page-sizes="[1, 2, 3]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :total="firstFrom.total">
      </el-pagination>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
export default {
  methods: {
    handleCurrentChange(currentPage) {
      this.pageFrom.page = currentPage;
      // 每次更改都要请求一次tabledata数据，在后端做数据分页！>.<
      this.getOwnCourse();

    },
    handleSizeChange(size) {
      this.pageFrom.pageSize = size;
      // 每次更改都要请求一次tabledata数据，在后端做数据分页！>.<！
       this.getOwnCourse()
    },
    async getOwnCourse() {
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`// Custom request header
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/teacher/course/page`,JSON.stringify(this.pageFrom),config);
      if (res.status !== 500) {
        this.tableData=res.data.records;
      } else {
        this.$message.error('获取课程失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('请求失败');
  }
},  
// 获取所有数据并保存
    async getOwnFirstCourse() {
    // JSON化
    this.pageFrom.pageSize=10
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`// Custom request header
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/teacher/course/page`,JSON.stringify(this.pageFrom),config);
      if (res.status !== 500) {
        this.$message.success('成功获取课程列表');
        this.tableData=res.data.records;
        this.firstFrom.total = res.data.total; // 保存总条数

      } else {
        this.$message.error('出错了，请联系管理员');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('你还没有开设课程');
  }
},
//搜索功能
    async searchCourse() {
      // 在这里执行你想要的点击事件的逻辑,
      const dataToSerialize = { ...this.pageFrom };
if (this.courseName) {
    dataToSerialize.courseName = this.courseName;
}
    // JSON化
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'token':`${localStorage.getItem("token")}`// Custom request header
      }
    };
    try {
      const { data: res } = await this.$http.post(`api/teacher/course/page`,JSON.stringify(dataToSerialize),config);
      if (res.status !== 500) {
        this.$message.success('成功查询');
        this.tableData=res.data.records;
        this.firstFrom.total = res.data.total;
      } else {
        this.$message.error('获取失败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('请求失败');
  }
},
    handleDelete(row) {
      if (confirm("是否确认删除？")) {
        this.deletecourseInfo(row.courseId);
      }
    },
    //删除课程信息,还可以检索名字
    async deletecourseInfo(ID) {
      const dataToSerialize = {};
      if (ID) {
    dataToSerialize.courseId=ID;
}
        if (this.pageFrom.id) {
        dataToSerialize.teacherId=this.pageFrom.id;
    }
    // JSON化
    const config = {
      headers: {
          'Content-Type': 'application/json',
          'token':`${localStorage.getItem("token")}`// Custom request header
        }
      };
    try {
      const { data: res } = await this.$http.delete('api/teacher/course/delete',{data:JSON.stringify(dataToSerialize), // 请求数据
    headers: config.headers })
      if (res.status !== 500) {
        this.$message.success('成功删除课程信息');
        // 重新调用获取表格的代码
        this.getOwnFirstCourse();
      } else {
        this.$message.error('删除失1败');
      }
    } catch (error) {
      // Handle request error
      console.error('Request Error:', error);
      this.$message.error('删除失败');
  }
    },

  },

  data() {
    return {
      tableData: [
],
      firstFrom:{
        // 用于保存初始的条数
      total:0,
      },
      pageFrom:{
      page: 1,
      pageSize: 2,
      id:'',
      // 要传给后端的数据
      },
      // 用于成绩查询的检索
      courseName:'',
      courseId:'',
      total: 0,
    }
  },
  created() {
     // 初始化操作
    if(localStorage.getItem("type") !== 'teacher'){this.$router.push(`/login`);this.$message.error('你不是老师');}
    this.name = localStorage.getItem('name');
    this.pageFrom.id = localStorage.getItem('teacherId');
    this.getOwnFirstCourse();
  },
  


}
</script>

<style lang="less" scoped>
  .el-row{
    margin-bottom: 30px;
  }
</style>